const fs = require('fs');
const { promisify } = require('util');
const { createToken } = require('../util/jwt');
const { User, Subscribe } = require('../model/index');
const lodash = require('lodash');
const rename = promisify(fs.rename);
exports.list = (req, res) => {
    res.send('/user-list');
};

exports.getchannel = async (req, res) => {
    let channelList = await Subscribe.find({
        channel: req.user.userinfo._id
    }).populate('user');
    channelList = channelList.map((item) => {
        return lodash.pick(item.user, [
            '_id',
            'username',
            'image',
            'subscribeCount',
            'cover',
            'channelIds'
        ]);
    });
    res.status(200).json(channelList);
};
// 获取关注列表
exports.getsubscribe = async (req, res) => {
    let subscribeList = await Subscribe.find({
        user: req.params.userId
    }).populate('channel');
    subscribeList = subscribeList.map((item) => {
        return lodash.pick(item.channel, [
            '_id',
            'username',
            'image',
            'subscribeCount',
            'cover',
            'channelIds'
        ]);
    });
    res.status(200).json(subscribeList);
};

// 注册账号
exports.register = async (req, res) => {
    const userModel = new User(req.body);
    const dbBack = await userModel.save();
    const user = dbBack.toJSON();
    delete user.password;
    res.status(200).json({
        user
    });
};

// 登录
exports.login = async (req, res) => {
    // 客户端数据验证
    // 链接数据库查询
    let user = await User.findOne(req.body);
    if (!user) {
        return res.status(402).json({ error: '邮箱或密码错误!' });
    }
    user = user.toJSON();
    // 生成jwt token
    user.token = await createToken(user);
    res.status(200).json(user);
};

exports.list = async (req, res) => {
    console.log(req.user);
    res.json('user-list');
};

// 用户修改
exports.update = async (req, res) => {
    console.log(req.user);
    const id = req.user.userinfo._id;
    // {new:true}返回新数据，否则会返回旧数据
    const updateData = await User.findByIdAndUpdate(id, req.body, { new: true });
    res.status(200).json({ user: updateData });
};

exports.headimg = async (req, res) => {
    const fileArr = req.file.originalname.split('.');
    const fileType = fileArr[fileArr.length - 1];
    try {
        // 重命名
        const originalname = `./public/${req.file.filename}`;
        const newName = `./public/${req.file.filename}.${fileType}`;
        await rename(originalname, newName);
        res.status(201).json({
            filepath: `${req.file.filename}.${fileType}`
        });
    } catch (error) {
        res.status(500).json({ error });
    }
};

exports.subscribe = async (req, res) => {
    const userId = req.user.userinfo._id;
    const channelId = req.params.userId;
    if (userId === channelId) {
        res.status(401).json({ err: '不能关注自己' });
    }

    const record = await Subscribe.findOne({
        user: userId,
        channel: channelId
    });
    if (!record) {
        await new Subscribe({
            user: userId,
            channel: channelId
        }).save();
        // 更新user的subscribeCount
        const user = await User.findById(channelId);
        user.subscribeCount++;
        await user.save();
        res.status(200).json({ msg: '关注成功' });
    } else {
        res.status(401).json({ err: '已经订阅了此频道' });
    }
};

// 取消关注
exports.unsubscribe = async (req, res) => {
    const userId = req.user.userinfo._id;
    const channelId = req.params.userId;
    if (userId === channelId) {
        res.status(401).json({ err: '不能取消关注自己' });
    }

    try {
        await Subscribe.deleteOne({
            user: userId,
            channel: channelId
        });
        const user = await User.findById(channelId);
        user.subscribeCount--;
        await user.save();
        res.status(200).json(user);
    } catch (error) {
        res.status(401).json({ err: '您还没有关注此频道' });
    }
};

exports.getuser = async (req, res) => {
    let isSubscribe = false;
    if (req.user) {
        const record = await Subscribe.findOne({
            channel: req.params.userId,
            user: req.user.userinfo._id
        });
        if (record) {
            isSubscribe = true;
        }
        const user = await User.findById(req.params.userId);
        user.isSubscribe = isSubscribe;
        res.status(200).json({
            ...lodash.pick(user, [
                '_id',
                'username',
                'image',
                'subscribeCount',
                'cover',
                'channelIds'
            ]),
            isSubscribe
        });
    }
};
